<template>
  <div class="realtime-dashboard">
    <!-- 连接状态指示器 -->
    <div class="connection-status">
      <el-tag :type="connectionStatusType" size="small">
        <el-icon class="status-icon">
          <component :is="connectionIcon" />
        </el-icon>
        {{ connectionStatus }}
      </el-tag>
      <el-button 
        v-if="connectionStatus === 'Disconnected'" 
        @click="reconnect" 
        type="primary" 
        size="small"
        :loading="isReconnecting"
      >
        重连
      </el-button>
    </div>

    <!-- 数据时间戳 -->
    <div class="data-timestamp">
      <span>数据更新时间: {{ lastUpdateTime }}</span>
    </div>

    <!-- 库存占比图表 -->
    <el-row :gutter="20" class="inventory-charts">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>库存数量占比</span>
              <el-tag size="small">{{ inventoryData.totalQuantity }} 件</el-tag>
            </div>
          </template>
          <div ref="quantityChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>库存金额占比</span>
              <el-tag size="small" type="success">¥{{ inventoryData.totalAmount.toFixed(2) }}</el-tag>
            </div>
          </template>
          <div ref="amountChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 入库出库统计图表 -->
    <el-row :gutter="20" class="statistics-charts">
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>入库统计</span>
              <el-tag size="small">{{ inboundData.timeRange }}</el-tag>
              <div class="summary-info">
                <span>总计: {{ inboundData.summary.totalQuantity }} 件</span>
                <span>金额: ¥{{ inboundData.summary.totalAmount.toFixed(2) }}</span>
              </div>
            </div>
          </template>
          <div ref="inboundChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>出库统计</span>
              <el-tag size="small" type="warning">{{ outboundData.timeRange }}</el-tag>
              <div class="summary-info">
                <span>总计: {{ outboundData.summary.totalQuantity }} 件</span>
                <span>金额: ¥{{ outboundData.summary.totalAmount.toFixed(2) }}</span>
              </div>
            </div>
          </template>
          <div ref="outboundChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 排行榜表格 -->
    <el-row :gutter="20" class="ranking-tables">
      <el-col :span="12">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>入库排行榜</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
          </template>
          <el-table 
            :data="rankingData.inboundRanking" 
            stripe 
            size="small"
            max-height="300"
          >
            <el-table-column prop="rank" label="排名" width="60" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="getRankTagType(row.rank)" 
                  size="small" 
                  round
                >
                  {{ row.rank }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" show-overflow-tooltip />
            <el-table-column prop="quantity" label="数量" width="80" align="right" />
            <el-table-column prop="amount" label="金额" width="100" align="right">
              <template #default="{ row }">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="次数" width="60" align="right" />
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="12">
        <el-card class="table-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>出库排行榜</span>
              <el-icon><TrendCharts /></el-icon>
            </div>
          </template>
          <el-table 
            :data="rankingData.outboundRanking" 
            stripe 
            size="small"
            max-height="300"
          >
            <el-table-column prop="rank" label="排名" width="60" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="getRankTagType(row.rank)" 
                  size="small" 
                  round
                >
                  {{ row.rank }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" show-overflow-tooltip />
            <el-table-column prop="quantity" label="数量" width="80" align="right" />
            <el-table-column prop="amount" label="金额" width="100" align="right">
              <template #default="{ row }">
                ¥{{ row.amount.toFixed(2) }}
              </template>
            </el-table-column>
            <el-table-column prop="count" label="次数" width="60" align="right" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 系统消息面板 -->
    <el-card class="message-card" shadow="hover" v-if="systemMessages.length > 0">
      <template #header>
        <div class="card-header">
          <span>系统消息</span>
          <el-badge :value="systemMessages.length" class="message-badge" />
        </div>
      </template>
      <div class="message-list">
        <div 
          v-for="message in systemMessages.slice(0, 5)" 
          :key="message.id"
          class="message-item"
          :class="`message-${message.type}`"
        >
          <el-icon class="message-icon">
            <component :is="getMessageIcon(message.type)" />
          </el-icon>
          <div class="message-content">
            <div class="message-title">{{ message.title }}</div>
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { 
  Connection, 
  Notification, 
  TrendCharts, 
  Warning, 
  SuccessFilled, 
  InfoFilled, 
  CircleCloseFilled 
} from '@element-plus/icons-vue'
import dashboardSignalRService, { 
  type InventoryProportionData,
  type InboundStatisticsData,
  type OutboundStatisticsData,
  type RankingData,
  type SystemMessage
} from '@/services/dashboardSignalRService'

// 图表引用
const quantityChartRef = ref<HTMLElement>()
const amountChartRef = ref<HTMLElement>()
const inboundChartRef = ref<HTMLElement>()
const outboundChartRef = ref<HTMLElement>()

// 图表实例
let quantityChart: echarts.ECharts | null = null
let amountChart: echarts.ECharts | null = null
let inboundChart: echarts.ECharts | null = null
let outboundChart: echarts.ECharts | null = null

// 响应式数据
const connectionStatus = ref('Disconnected')
const isReconnecting = ref(false)
const lastUpdateTime = ref('')

// 仪表板数据
const inventoryData = reactive<InventoryProportionData>({
  timestamp: '',
  quantityData: [],
  amountData: [],
  totalQuantity: 0,
  totalAmount: 0
})

const inboundData = reactive<InboundStatisticsData>({
  timestamp: '',
  timeRange: '最近7天',
  chartData: [],
  summary: {
    totalQuantity: 0,
    totalAmount: 0,
    totalCount: 0,
    avgQuantity: 0,
    avgAmount: 0
  }
})

const outboundData = reactive<OutboundStatisticsData>({
  timestamp: '',
  timeRange: '最近7天',
  chartData: [],
  summary: {
    totalQuantity: 0,
    totalAmount: 0,
    totalCount: 0,
    avgQuantity: 0,
    avgAmount: 0
  }
})

const rankingData = reactive<RankingData>({
  timestamp: '',
  inboundRanking: [],
  outboundRanking: []
})

const systemMessages = ref<SystemMessage[]>([])

// 计算属性
const connectionStatusType = computed(() => {
  switch (connectionStatus.value) {
    case 'Connected': return 'success'
    case 'Connecting': 
    case 'Reconnecting': return 'warning'
    case 'Disconnected': return 'danger'
    default: return 'info'
  }
})

const connectionIcon = computed(() => {
  switch (connectionStatus.value) {
    case 'Connected': return Connection
    case 'Connecting':
    case 'Reconnecting': return Notification
    default: return CircleCloseFilled
  }
})

// 🔥 核心：Watch监听数据变化
watch(() => inventoryData.quantityData, (newData) => {
  if (newData.length > 0 && quantityChart) {
    console.log('库存数量占比数据变化，更新图表')
    updateQuantityChart(newData)
  }
}, { deep: true })

watch(() => inventoryData.amountData, (newData) => {
  if (newData.length > 0 && amountChart) {
    console.log('库存金额占比数据变化，更新图表')
    updateAmountChart(newData)
  }
}, { deep: true })

watch(() => inboundData.chartData, (newData) => {
  if (newData.length > 0 && inboundChart) {
    console.log('入库统计数据变化，更新图表')
    updateInboundChart(newData)
  }
}, { deep: true })

watch(() => outboundData.chartData, (newData) => {
  if (newData.length > 0 && outboundChart) {
    console.log('出库统计数据变化，更新图表')
    updateOutboundChart(newData)
  }
}, { deep: true })

watch(() => rankingData.inboundRanking, (newData) => {
  console.log('入库排行榜数据变化:', newData.length, '条记录')
}, { deep: true })

watch(() => rankingData.outboundRanking, (newData) => {
  console.log('出库排行榜数据变化:', newData.length, '条记录')
}, { deep: true })

watch(() => systemMessages.value, (newMessages) => {
  console.log('系统消息变化:', newMessages.length, '条消息')
  if (newMessages.length > 0) {
    lastUpdateTime.value = formatTime(new Date().toISOString())
  }
}, { deep: true })

// 组件挂载
onMounted(async () => {
  console.log('仪表板组件挂载，开始初始化...')
  
  // 初始化图表
  await nextTick()
  initCharts()
  
  // 连接SignalR
  await connectSignalR()
  
  // 窗口大小变化时重新调整图表
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(async () => {
  console.log('仪表板组件卸载，清理资源...')
  
  // 销毁图表
  quantityChart?.dispose()
  amountChart?.dispose()
  inboundChart?.dispose()
  outboundChart?.dispose()
  
  // 断开SignalR
  await dashboardSignalRService.disconnect()
  
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})

// 初始化图表
const initCharts = () => {
  console.log('初始化图表...')
  
  if (quantityChartRef.value) {
    quantityChart = echarts.init(quantityChartRef.value)
    quantityChart.setOption(getPieChartOption('库存数量分布'))
  }
  
  if (amountChartRef.value) {
    amountChart = echarts.init(amountChartRef.value)
    amountChart.setOption(getPieChartOption('库存金额分布'))
  }
  
  if (inboundChartRef.value) {
    inboundChart = echarts.init(inboundChartRef.value)
    inboundChart.setOption(getBarChartOption('入库统计', '#5470c6'))
  }
  
  if (outboundChartRef.value) {
    outboundChart = echarts.init(outboundChartRef.value)
    outboundChart.setOption(getBarChartOption('出库统计', '#ee6666'))
  }
}

// 连接SignalR
const connectSignalR = async () => {
  console.log('连接SignalR服务...')
  
  // 注册事件回调
  dashboardSignalRService.onInventoryProportion((data) => {
    console.log('收到库存占比数据:', data)
    Object.assign(inventoryData, data)
    lastUpdateTime.value = formatTime(new Date().toISOString())
  })
  
  dashboardSignalRService.onInboundStatistics((data) => {
    console.log('收到入库统计数据:', data)
    Object.assign(inboundData, data)
    lastUpdateTime.value = formatTime(new Date().toISOString())
  })
  
  dashboardSignalRService.onOutboundStatistics((data) => {
    console.log('收到出库统计数据:', data)
    Object.assign(outboundData, data)
    lastUpdateTime.value = formatTime(new Date().toISOString())
  })
  
  dashboardSignalRService.onRankingData((data) => {
    console.log('收到排行榜数据:', data)
    Object.assign(rankingData, data)
    lastUpdateTime.value = formatTime(new Date().toISOString())
  })
  
  dashboardSignalRService.onSystemMessages((messages) => {
    console.log('收到系统消息:', messages)
    systemMessages.value = messages
  })
  
  dashboardSignalRService.onConnectionStateChange((state) => {
    console.log('连接状态变化:', state)
    connectionStatus.value = state
  })
  
  // 建立连接
  try {
    const connected = await dashboardSignalRService.connect()
    if (connected) {
      connectionStatus.value = 'Connected'
      // 请求初始数据
      await dashboardSignalRService.requestLatestData()
    } else {
      connectionStatus.value = 'Disconnected'
    }
  } catch (error) {
    console.error('连接SignalR失败:', error)
    connectionStatus.value = 'Disconnected'
  }
}

// 重连
const reconnect = async () => {
  isReconnecting.value = true
  connectionStatus.value = 'Connecting'
  
  try {
    const connected = await dashboardSignalRService.connect()
    if (connected) {
      connectionStatus.value = 'Connected'
    }
  } finally {
    isReconnecting.value = false
  }
}

// 更新图表方法
const updateQuantityChart = (data: any[]) => {
  if (!quantityChart) return
  
  quantityChart.setOption({
    series: [{
      data: data.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: { color: item.color || getRandomColor() }
      }))
    }]
  })
}

const updateAmountChart = (data: any[]) => {
  if (!amountChart) return
  
  amountChart.setOption({
    series: [{
      data: data.map(item => ({
        name: item.name,
        value: item.value,
        itemStyle: { color: item.color || getRandomColor() }
      }))
    }]
  })
}

const updateInboundChart = (data: any[]) => {
  if (!inboundChart) return
  
  const dates = data.map(item => item.date.split('-').slice(1).join('/'))
  const quantities = data.map(item => item.quantity)
  
  inboundChart.setOption({
    xAxis: { data: dates },
    series: [{ data: quantities }]
  })
}

const updateOutboundChart = (data: any[]) => {
  if (!outboundChart) return
  
  const dates = data.map(item => item.date.split('-').slice(1).join('/'))
  const quantities = data.map(item => item.quantity)
  
  outboundChart.setOption({
    xAxis: { data: dates },
    series: [{ data: quantities }]
  })
}

// 图表配置选项
const getPieChartOption = (title: string) => ({
  title: {
    text: title,
    left: 'center',
    top: 20,
    textStyle: { fontSize: 14 }
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    type: 'scroll',
    orient: 'vertical',
    right: 10,
    top: 20,
    bottom: 20
  },
  series: [{
    name: title,
    type: 'pie',
    radius: ['40%', '70%'],
    center: ['40%', '50%'],
    avoidLabelOverlap: false,
    label: {
      show: false,
      position: 'center'
    },
    emphasis: {
      label: {
        show: true,
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    labelLine: {
      show: false
    },
    data: []
  }]
})

const getBarChartOption = (title: string, color: string) => ({
  title: {
    text: title,
    left: 'center',
    textStyle: { fontSize: 14 }
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: { type: 'shadow' }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: [],
    axisTick: { alignWithLabel: true }
  },
  yAxis: {
    type: 'value'
  },
  series: [{
    name: '数量',
    type: 'bar',
    barWidth: '60%',
    itemStyle: { color: color },
    data: []
  }]
})

// 工具方法
const handleResize = () => {
  quantityChart?.resize()
  amountChart?.resize()
  inboundChart?.resize()
  outboundChart?.resize()
}

const getRankTagType = (rank: number) => {
  if (rank === 1) return 'danger'
  if (rank === 2) return 'warning'
  if (rank === 3) return 'success'
  return 'info'
}

const getMessageIcon = (type: string) => {
  switch (type) {
    case 'error': return CircleCloseFilled
    case 'warning': return Warning
    case 'success': return SuccessFilled
    default: return InfoFilled
  }
}

const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleString('zh-CN')
}

const getRandomColor = () => {
  const colors = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4']
  return colors[Math.floor(Math.random() * colors.length)]
}
</script>

<style scoped>
.realtime-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  /* 确保页面布局不受Dify智能体影响 */
  width: 100%;
  max-width: 100%;
  box-sizing: border-box;
}

.connection-status {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: 10px;
}

.status-icon {
  margin-right: 4px;
}

.data-timestamp {
  text-align: center;
  margin-bottom: 20px;
  color: #666;
  font-size: 12px;
}

.inventory-charts,
.statistics-charts,
.ranking-tables {
  margin-bottom: 20px;
}

.chart-card,
.table-card {
  height: 400px;
}

.chart-container {
  height: 320px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 8px;
}

.summary-info {
  display: flex;
  gap: 15px;
  font-size: 12px;
  color: #666;
}

.message-card {
  margin-top: 20px;
}

.message-badge {
  margin-left: 10px;
}

.message-list {
  max-height: 200px;
  overflow-y: auto;
}

.message-item {
  display: flex;
  align-items: flex-start;
  padding: 10px;
  border-left: 4px solid #ddd;
  margin-bottom: 10px;
  background-color: #fafafa;
  border-radius: 4px;
}

.message-item.message-error {
  border-left-color: #f56c6c;
  background-color: #fef0f0;
}

.message-item.message-warning {
  border-left-color: #e6a23c;
  background-color: #fdf6ec;
}

.message-item.message-success {
  border-left-color: #67c23a;
  background-color: #f0f9ff;
}

.message-item.message-info {
  border-left-color: #409eff;
  background-color: #ecf5ff;
}

.message-icon {
  margin-right: 10px;
  margin-top: 2px;
  font-size: 16px;
}

.message-content {
  flex: 1;
}

.message-title {
  font-weight: bold;
  margin-bottom: 4px;
}

.message-text {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.message-time {
  font-size: 12px;
  color: #999;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .realtime-dashboard {
    padding: 10px;
    /* 移除底部边距，因为现在只有小图标 */
    margin-bottom: 2rem;
  }
  
  .inventory-charts .el-col,
  .statistics-charts .el-col,
  .ranking-tables .el-col {
    margin-bottom: 20px;
  }
}

/* 确保与Dify智能体兼容 */
.realtime-dashboard {
  /* 移除底部边距，因为现在只有小图标 */
  margin-bottom: 2rem;
  min-height: calc(100vh - 2rem);
}

/* 在小屏幕上进一步调整 */
@media (max-width: 480px) {
  .realtime-dashboard {
    margin-bottom: 2rem;
    padding: 5px;
  }
}
</style>
